<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UserController
 *
 * @author wangnaixin
 */
namespace Admin\Controller;

use Admin\Model\UserModel;
use Admin\Model\RoleModel;
use Admin\Controller\AdminController;

/**
 * @author wangnaixin
 * @todo 用户模块
 * @menu 用户管理
 * @menuAuto index
 * @order 45
 * @autoCheck index,getAuthList
 * @icon user.png
 */
class UserController extends AdminController {
    //put your code here
    
    
    public $user;
    public $user_id;
    public $role;
    function __construct() {
        parent::__construct();
        $this->user_id = I('userId');
        $this->role = new RoleModel();
        $this->user = new UserModel();
    }


    
    /**
     * @author hotterWang
     * @todo 用户列表
     * @menu 用户列表
     * @order 10
     */
    public function index(){
        //处理查询条件
        $this->setForm();
        $where = [];
        if(IS_POST){
            if(I('real_name')){
                $where['real_name'] = array('eq',I('real_name'));
            }
            if(I('mobile')){
                $where['mobile'] = array('eq',I('mobile'));
            }
            $status = I('status');
            if(isset($status) && $status !== '-1'){
                $where['status'] = array('eq',I('status'));
            }
            if(I('role_id')){
                $where['role_id'] = array('eq',I('role_id'));
            }
            if(I('team_id')){
                $where['team_id'] = array('eq',I('team_id'));
            }
        }
        
        if ($this->userTeamMemberIds != 0) {
            if ($this->userTeamMemberIds)  {
                $where['id'] = array('in',$this->userTeamMemberIds);
            } else {
                $where['id'] = 0;
            }
        }
        $data = $this->user->getUserList($where);
        $this->assign("data",$data);
        $roleList = $this->getRoleList();
        $this->assign("roleList",$roleList);
        if ($this->defaultSysModule == 'Space') {
            $this->assign('teamList', $this->getTeamList());
        }
        $this->display();
    }
    
    
    /**
     * @todo 禁用用户
     */
    public function deUser(){
        $this->user->deUserById($this->user_id);
        $this->ajaxReturn(true);
    }
    
    /**
     * @todo 密码重置
     */
    public function resetUserPass(){
        $this->user->resetUserPass($this->user_id);
        $this->ajaxReturn(true);
    }
    
    /**
     * @todo 启用用户
     */
    public function enUser(){
        $this->user->enUserById($this->user_id);
        $this->ajaxReturn(true);
    }
    
    /**
     * @todo 用户添加
     */
    public function addUser(){
        $roleList = $this->getRoleList();
        $this->assign("roleList",$roleList);
        if ($this->defaultSysModule == 'Space') {
            $this->assign('teams',$this->getTeamList());
            $this->assign('saveUrl',U('Admin/User/doAddUser'));
            $this->display('add');
        } else {
            $this->display();
        }
    }
    
    /**
     * @todo 用户添加操作
     */
    public function doAddUser(){
        if ($this->defaultSysModule == 'Space') {
            $this->doSaveUser();
        }
        $response = array('status' => false, 'msg' => '用户添加失败!');
        $password = I('password');
        if(empty($password)){
            $_POST['password'] = '123456';
        }
        $roleInfo = $this->role->getRoleInfoById($_POST['role_id']);
        if ($roleInfo['super'] != 1) {
            $_POST['module'] = session('default_module');
        }
        $data = $this->user->create();
        if($data !== false){
            if ($this->user->checkExists('user_name',$_POST['user_name'])) {
                $response['msg'] = '该用户名称已经存在';
                $this->ajaxReturn($response);
            }
            if ($this->user->checkExists('mobile',$_POST['mobile'])) {
                $response['msg'] = '该手机号码已经存在';
                $this->ajaxReturn($response);
            }
            if ($this->user->checkExists('email',$_POST['email'])) {
                $response['msg'] = '该邮箱地址已经存在';
                $this->ajaxReturn($response);
            }
            if ($this->user->checkExists('identity',$_POST['identity'])) {
                $response['msg'] = '该身份证号已经存在';
                $this->ajaxReturn($response);
            }
            if($this->user->add()){
                $response['status'] = true;
                $response['msg'] = '用户添加成功!';
                $this->ajaxReturn($response);
            }else{
                $this->ajaxReturn($response);
            }
        }else{
            $this->ajaxReturn($response);
        }
    }
    
    /**
     * @todo 修改用户
     */
    public function editUser(){
        $userInfo = $this->user->getUserInfoById($this->user_id);
        $roleList = $this->getRoleList();
        $this->assign("roleList",$roleList);
        $this->assign("user",$userInfo);
        if ($this->defaultSysModule == 'Space') {
            $this->assign('teams',$this->getTeamList());
            $this->assign('saveUrl',U('Admin/User/doEditUser'));
            $this->display('add');
        } else {
            $this->display();
        }
    }
    
    /**
     * @todo 修改用户操作
     */
    public function doEditUser(){
        if ($this->defaultSysModule == 'Space') {
            $this->doSaveUser();
        }
        $response = array('status' => false, 'msg' => '用户修改失败!');
        $password = I('password');
        $roleInfo = $this->role->getRoleInfoById($_POST['role_id']);
        if ($roleInfo['super'] == 1) {
            $_POST['module'] = '';
        } else {
            $_POST['module'] = session('default_module');
        }
        $data = $this->user->create();
        if($data !== false){
            if(empty($password)){
                unset($data['password']);
            }
            if ($this->user->checkExists('user_name',$_POST['user_name'],$this->user_id)) {
                $response['msg'] = '该用户名称已经存在';
                $this->ajaxReturn($response);
            }
            if ($this->user->checkExists('mobile',$_POST['mobile'],$this->user_id)) {
                $response['msg'] = '该手机号码已经存在';
                $this->ajaxReturn($response);
            }
            if ($this->user->checkExists('email',$_POST['email'],$this->user_id)) {
                $response['msg'] = '该邮箱地址已经存在';
                $this->ajaxReturn($response);
            }
            if ($this->user->checkExists('identity',$_POST['identity'],$this->user_id)) {
                $response['msg'] = '该身份证号已经存在';
                $this->ajaxReturn($response);
            }
            if($this->user->where("id = ".$this->user_id)->save($data)){
                $response['status'] = true;
                $response['msg'] = '用户修改成功!';
                $this->ajaxReturn($response);
            }else{
                $this->ajaxReturn($response);
            }
            
        }else{
            $this->ajaxReturn($response);
        }
    }

    /**
     * 获取可用的角色列表
     * @return mixed
     */
    private function getRoleList() {
        
        switch ($this->userInfo['role']['id']) {
            case C('AREA_ADMIN_ROLE_ID'):
            case C('SPACE_ADMIN_ROLE_ID'):
                $where['id'] = array('not in',array(1));
                break;
            case C('TEAM_ADMIN_ROLE_ID'):
                $where['id'] = array('not in',array(1,C('SPACE_ADMIN_ROLE_ID')));
                break;
        }
        $roleList = $this->role->getList($where);
        return $roleList;
    }

    private function doSaveUser(){
        $response = array('status' => false, 'msg' => '用户添加失败!');
        $userId = $this->user_id;
        $roleId = I('role_id');
        $teamId = I('team_id');
        $mobile = I('mobile');
        if ($this->user->checkExists('user_name',$_POST['user_name'],$userId)) {
            $response['msg'] = '该用户名称已经存在';
            $this->ajaxReturn($response);
        }
        if ($this->user->checkExists('mobile',$_POST['mobile'],$userId)) {
            $response['msg'] = '该手机号码已经存在';
            $this->ajaxReturn($response);
        }
        if ($this->user->checkExists('email',$_POST['email'],$userId)) {
            $response['msg'] = '该邮箱地址已经存在';
            $this->ajaxReturn($response);
        }
        if ($this->user->checkExists('identity',$_POST['identity'],$userId)) {
            $response['msg'] = '该身份证号已经存在';
            $this->ajaxReturn($response);
        }
        //修改
        if($userId){
            $response['msg'] = '用户修改失败!';
            $data = array(
                'user_name' => $mobile,
                'real_name' => I('real_name'),
                'mobile'    => $mobile,
                'identity'  => I('identity'),
                'position'  => I('position'),
                'remark'    => I('remark'),
                'email'     => I('email'),
                'role_id'   => $roleId
            );
            if (in_array($roleId,array(C('TEAM_ADMIN_ROLE_ID'),C('TEAM_MEMBER_ROLE_ID'))) && !$teamId) {
                $response['msg'] = '请选择所属团队';
                $this->ajaxReturn($response);
            }
            if ($teamId) {
                $data['team_id'] = $teamId;
            }
            $rs = $this->user->where(['id'=>$userId])->save($data);
            if ($rs !== false) {
                $this->setUserTeam($userId,$roleId);
                $response['status'] = true;
                $response['msg'] = '用户修改成功!';
            }
            $this->ajaxReturn($response);
        }
        //添加
        $data = array(
            'user_name' => $mobile,
            'real_name' => I('real_name'),
            'password'  => md5($mobile),
            'mobile'    => $mobile,
            'create_time' => time(),
            'module'    => 'Space',
            'user_type' => 1,
            'identity'  => I('identity'),
            'position'  => I('position'),
            'remark'    => I('remark'),
            'email'     => I('email'),
            'role_id'   => $roleId
        );
        if (in_array($roleId,array(C('TEAM_ADMIN_ROLE_ID'),C('TEAM_MEMBER_ROLE_ID'))) && !$teamId) {
            $response['msg'] = '请选择所属团队';
            $this->ajaxReturn($response);
        }
        if ($teamId) {
            $data['team_id'] = $teamId;
        }
        if ($teamId) {
            $data['team_id'] = $teamId;
        }
        $uid = $this->user->add($data);
        if ($uid) {
            $this->setUserTeam($uid,$roleId);
            $response['status'] = true;
            $response['msg'] = '用户添加成功!';
        }
        $this->ajaxReturn($response);
    }

    public function modifyPwd() {
        $id = $this->userId;
        if ($_POST['submitForm']) {
            $response = array('status' => false, 'msg' => '密码修改失败!');
            $pwd = I('pwd');
            $pwd1 = I('pwd1');
            if (!$pwd && !$pwd1) {
                $response['msg'] = '您的新密码不能为空!';
                $this->ajaxReturn($response);
            }
            if (strcmp($pwd,$pwd1) == 0) {
                $rs = $this->user->where(array('id'=>$id))->save(array('password'=>md5($pwd)));
                if ($rs !== false) {
                    $response['status'] = true;
                    $response['msg'] = '密码修改成功!';
                    $this->ajaxReturn($response);
                }
                $this->ajaxReturn($response);
            }
            $response['msg'] = '两次输入的密码不一致，请确认!';
            $this->ajaxReturn($response);
        }
        $this->display();
    }

    private function setUserTeam($userId,$roleId) {
        $teamId = I('team_id');
        M('user_team')->where([
            'user_id'=>$userId,
            'team_id'=>$teamId
        ])->delete();
        if($roleId == C('TEAM_ADMIN_ROLE_ID')) {
            M('user_team')->add([
                'user_id'=>$userId,
                'team_id'=>$teamId
            ]);
        }
    }

    /**
     * 获取可用的团队列表
     * @return mixed
     */
    private function getTeamList(){
        $where = array(
            'is_delete' => 0
        );
        if ($this->userTeamIds != 0) {
            if ($this->userTeamIds)  {
                $where['id'] = array('in',$this->userTeamIds);
            } else {
                $where['id'] = 0;
            }
        }
        $teams = M('team')->where($where)->field('id,team_name')->order('convert(team_name using gbk) asc')->select();
        return $teams;
    }
}
